# views.py
from django.http import JsonResponse
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.contrib.auth.models import User
from flask import Response
from rest_framework import status
from utils.ranking_service import RankingService
from .models import UserPoints

# @method_decorator(csrf_exempt, name='dispatch')
class PointsUpdateView(View):
    """更新用户积分"""
    def post(self, request, *args, **kwargs):
        user_id = request.POST.get('user_id')
        points = int(request.POST.get('points'))
        reason = request.POST.get('reason', 'system')

        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return JsonResponse({'message': "没有查到用户信息"}, status=404)

        # 更新 Redis 排名
        service = RankingService()
        service.update_points(user_id, points, reason)

        return JsonResponse({
            'user_id': user_id,
            'new_points': service.get_score(user_id),
            'rank': service.get_rank(user_id)
        })

class UserRankingView(View):
    """获取用户排名信息"""
    def get(self, request, user_id, format=None):
        service = RankingService()
        score = service.get_score(user_id)
        rank = service.get_rank(user_id)

        if score is None or rank is None:
            return Response({'error': ''}, status=status.HTTP_404_NOT_FOUND)

        return Response({
            'user_id': user_id,
            'points': score,
            'rank': rank,
            'total_users': service.get_user_count()
        })

class TopUsersView(View):
    """获取排行榜前 N 名用户"""
    def get(self, request):
        limit = int(request.query_params.get('limit', 10))
        service = RankingService()
        top_users = service.get_top_users(limit)

        results = []
        for idx, (user_id, score) in enumerate(top_users, 1):
            try:
                user = User.objects.get(id=user_id)
                results.append({
                    'rank': idx,
                    'user_id': user_id,
                    'username': user.username,
                    'points': int(score)
                })
            except User.DoesNotExist:
                pass  # 处理用户已删除的情况
        return Response(results)